package com.teach.config;

import com.teach.CodeException;
import com.teach.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * <pre>
 * -
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2022-07-04 15:17
 * Version : 1.0
 * Copyright 2022 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 **/
@RestControllerAdvice
@Slf4j
public class CommonExceptionAdvice {

  @ResponseStatus(HttpStatus.OK)
  @ExceptionHandler(Exception.class)
  public R<?> handleException(Exception ex) {
    return R.error().setCode(0).setMessage(ex.getMessage());
  }

  @ResponseStatus(HttpStatus.OK)
  @ExceptionHandler(CodeException.class)
  public R<?> handleCodeException(CodeException ex) {
    return R.error().setCode(ex.getCode()).setMessage(ex.getMessage());
  }

  @ResponseStatus(HttpStatus.OK)
  @ExceptionHandler(NullPointerException.class)
  public R<?> HandleNullPointerException(NullPointerException ex) {
    log.error("空指针异常", ex);
    return R.error().setCode(0).setMessage("空指针异常");
  }

  @ResponseStatus(HttpStatus.OK)
  @ExceptionHandler(MethodArgumentNotValidException.class)
  public R<?> HandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
    FieldError fieldError = ex.getFieldError();
    if(fieldError==null){
      return R.error().setMessage("未知的校验错误");
    }
    return R.error().setCode(0).setMessage(fieldError.getDefaultMessage());
  }

  @ResponseStatus(HttpStatus.OK)
  @ExceptionHandler(ConstraintViolationException.class)
  public R<?> HandleConstraintViolationException(ConstraintViolationException ex) {
    Set<ConstraintViolation<?>> fieldError = ex.getConstraintViolations();
    if(fieldError==null || fieldError.size()==0){
      return R.error().setMessage("未知的校验错误");
    }
    return R.error().setCode(0).setMessage(fieldError.iterator().next().getMessage());
  }


}
